<?php


namespace app\controller\api;

use app\controller\api\Base;
use app\model\Attachment as AttachmentModel;
use app\model\RemarkModel;
use app\Request;
use think\App;
use think\db\exception\DbException;
use think\facade\Db;
use app\common\library\Translation;

class State extends Base
{
    public $token;
    public $version;
    public $lang;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->token = $this->request->header('xzdToken');
        $this->version = $this->request->header('version');
        $this->lang = $this->request->header('lang');
    }



    /**
     * @param Request $request
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 平台内容
     * @author: dongdong
     * @date: 2025/2/20 16:52
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;
        $page = ($page - 1) * $limit;

        $where = "is_deleted=0";
        $keyword = $param['keyword'] ?? '';
        $cate_id = $param['cate_id'] ?? '';
        if ($keyword) {
            $where .= " and (title like '%$keyword%' or title_ru like '%$keyword%')";
        }
        if ($cate_id) {
            $where .= " and cate_id = $cate_id";
        }

        $AttachmentModel = new AttachmentModel();

        $data = Db::table("store_state")->where($where)->order("id desc")->limit($page, $limit)->select();
        $arr = [];
        foreach ($data as $k => &$v) {
            $v['cate_name'] = Db::table("store_config")->where(['id' => $v['cate_id']])->field("title,title_ru")->find();
            $v['image'] = $AttachmentModel->lists('store_state', $v['image_id']);
            array_push($arr, $v);
        }
        $this->api_result(200, '请求成功', ['data' => $arr]);
    }


    /**
     * @param Request $request
     * @throws DbException
     * @notes 发布
     * @author: dongdong
     * @date: 2025/2/20 20:32
     */
    public function add(Request $request)
    {
        $param = $request->param();
        $d['user_id'] = $param['user_id'];
        $d['cate_id'] = $param['cate_id'];
        $d['score'] = $param['score'];

        $RemarkModel = new RemarkModel();
        $title_arr = $RemarkModel->translationAction($param['title'] ?? '');
        $d['title'] = $title_arr['zh'] ?? '';
        $d['title_ru'] = $title_arr['ru'] ?? '';

        $content_arr = $RemarkModel->translationAction($param['content'] ?? '');
        $d['content'] = $content_arr['zh'] ?? '';
        $d['content_ru'] = $content_arr['ru'] ?? '';

        $insertGetId = Db::table("store_state")->insertGetId($d);

        $AttachmentModel = new AttachmentModel();
        $str = '';
        $video = '';
        if (!empty($param['image'])) {
            $list_arr = explode(',', $param['image']);
            foreach ($list_arr as $k => &$v) {
                $str .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => "store_state", 'table_id' => $insertGetId, 'path' => $v]) . ',';
            }
            $str = trim($str, ',');
        }

        if (!empty($param['video'])) {
            $video_arr = explode(',', $param['video']);
            foreach ($video_arr as $k => &$v) {
                $video .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => "store_state", 'table_id' => $insertGetId, 'path' => $v]) . ',';
            }
            $video = trim($video, ',');
        }


        Db::table("store_state")->where(["id" => $insertGetId])->update(['image_id' => $str, 'video_id' => $video]);
        $this->api_result(200, '请求成功', ['data' => []]);
    }


    /**
     * @param Request $request
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 回显详情
     * @author: dongdong
     * @date: 2025/2/21 9:39
     */
    public function info(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $member_id = $param['user_id'];
        $data = Db::table("store_state")->where("id=$id")->find();
        Db::query("update store_state set num=num+1 where id=$id");
        if ($data) {
            $AttachmentModel = new AttachmentModel();
            $user_id = $data['user_id'];
            $data['cate_name'] = Db::table("store_config")->where(['id' => $data['cate_id']])->field("title,title_ru")->find();
            $data['member'] = Db::connect("fast_mysql")->table("fa_user")->where("id=$user_id")->field("id,username,username_ru,avatar,score,rating,level")->find();
            $user_info = Db::connect("fast_mysql")->table("fa_user_info")->where("user_id=$user_id")->field('rating,country,area_new_id')->find();
            $data['rating'] = $user_info['rating'];
            $data['country'] = $user_info['country'];
            $data['area'] = Db::connect("fast_mysql")->table("fa_area")->where(["id" => $user_info['area_new_id']])->find();
            $data['image'] = $AttachmentModel->lists('store_state', $data['image_id']);
            $data['video'] = $AttachmentModel->lists('store_state', $data['video_id']);
            $fa_user_guanzhu = Db::connect("fast_mysql")->table("fa_user_guanzhu")->where(['user_id' => $member_id, 'guanzhu_id' => $data['user_id']])->find();
            if ($fa_user_guanzhu) {
                $data['is_guanzhu'] = 1;
            } else {
                $data['is_guanzhu'] = 0;
            }

            $fa_user_score = Db::connect("fast_mysql")->table("fa_user_score_log")->where(['user_id' => $member_id,'lx'=>22 ,'child_user_id' => $param['id']])->find();
            if ($fa_user_score) {
                $data['is_pay_score'] = 1;
            } else {
                $data['is_pay_score'] = 0;
            }
            $this->api_result(200, '请求成功', ['data' => $data]);
        } else {
            $this->api_result(400, '请求失败', ['data' => []]);
        }
    }


    //积分选择
    public function score_select(){
        $this->api_result(200, '请求成功', ['data' => [100,200,300,400,500]]);
    }


    //扣除积分
    public function pay_score(Request $request)
    {
        $param = $request->param();
        $score = $param['score'] ?? 0;

        $d['user_id'] = $user_id = $param['user_id']??0;
        $pay_user_id = $param['pay_user_id']??0;
        $id = $param['id']??0;
        $lx = $param['lx'] ?? 22;

        $member = Db::connect("fast_mysql")->table("fa_user")->where("id=$user_id")->field("id,username,username_ru,avatar,score,rating,level")->find();
        if ($member['score'] >= $score) {
            $d['after'] = $member['score'] - $score;
            $d['before'] = $member['score'];
            $d['score'] = '-' .$param['score'] ?? 0;
            $d['memo'] = '支付积分 去除翻译官蒙版';
            $d['remark'] = '支付用户id: ' . $pay_user_id.', 内容id: '.$id;
            $d['child_user_id'] = $id;
            $d['lx'] = $lx;
            $d['createtime'] = time();

            Db::connect("fast_mysql")->table("fa_user_score_log")->insert($d);
            Db::connect("fast_mysql")->table("fa_user")->where(['id' => $user_id])->update(['score' => $d['after']]);

            $this->api_result(200, '请求成功', ['data' => []]);
        } else {
            $this->api_result(-1, '积分不足', ['data' => []]);
        }


    }


    /**
     * @param Request $request
     * @throws DbException
     * @notes 修改发布
     * @author: dongdong
     * @date: 2025/2/20 20:32
     */
    public function update(Request $request)
    {
        $param = $request->param();
        $insertGetId = $param['id'];

        $d['user_id'] = $param['user_id'];
        $d['cate_id'] = $param['cate_id'];
        $d['score'] = $param['score'];

        $RemarkModel = new RemarkModel();
        $title_arr = $RemarkModel->translationAction($param['title'] ?? '');
        $d['title'] = $title_arr['zh'] ?? '';
        $d['title_ru'] = $title_arr['ru'] ?? '';

        $content_arr = $RemarkModel->translationAction($param['content'] ?? '');
        $d['content'] = $content_arr['zh'] ?? '';
        $d['content_ru'] = $content_arr['ru'] ?? '';

        Db::table("store_state")->where(['id' => $insertGetId])->update($d);

        $AttachmentModel = new AttachmentModel();
        $str = '';
        $video = '';
        if (!empty($param['image'])) {
            $list_arr = explode(',', $param['image']);
            foreach ($list_arr as $k => &$v) {
                $str .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => "store_state", 'table_id' => $insertGetId, 'path' => $v]) . ',';
            }
            $str = trim($str, ',');
        }

        if (!empty($param['video'])) {
            $video_arr = explode(',', $param['video']);
            foreach ($video_arr as $k => &$v) {
                $video .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => "store_state", 'table_id' => $insertGetId, 'path' => $v]) . ',';
            }
            $video = trim($video, ',');
        }


        Db::table("store_state")->where(["id" => $insertGetId])->update(['image_id' => $str, 'video_id' => $video]);
        $this->api_result(200, '请求成功', ['data' => []]);
    }


    /**
     * @param Request $request
     * @throws DbException
     * @notes 删除
     * @author: dongdong
     * @date: 2025/2/21 9:51
     */
    public function del(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];

        $find = Db::connect("fast_mysql")->table("fa_user_score_log")->where("child_user_id=$id and lx=22")->find();
        if($find){
            $this->api_result(400, '请求失败,该服务已被购买', ['data' => []]);
        }else{
            Db::table("store_state")->where(["id" => $id])->update(['is_deleted' => 1]);
            $this->api_result(200, '请求成功', ['data' => []]);
        }
    }


    /**
     * @param Request $request
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 请求分钟
     * @author: dongdong
     * @date: 2025/2/21 10:06
     */
    public function request_minute(Request $request)
    {
        $param = $request->param();
        $user_id = $param['user_id'] ?? '';
        $id = $param['id'] ?? '';
        $minute = 0;
        $state = Db::table("store_state")->where(["id" => $id])->find();
        if ($state) {
            $state_user_id = $state['user_id'];
            $intention_score = Db::connect("fast_mysql")->table("fa_user_staff")->where("user_id=$state_user_id")->value('intention_score');
            if ($user_id) {
                $score = Db::connect("fast_mysql")->table("fa_user")->where("id=$user_id")->value('score');
                if ($intention_score) {
                    $minute = floor($score / $intention_score);
                } else {
                    $minute = 0;
                }
            }
        }
        $this->api_result(200, '请求成功', ['data' => $minute]);
    }


    /**
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 分类列表
     * @author: dongdong
     * @date: 2025/2/20 17:23
     */
    public function cate_list(Request $request)
    {
        $param = $request->param();
        $type = $param['type']??'';
        if($type!=1){
            $data = Db::table("store_config")->where("type=8")->field("id,title,title_ru")->select();
        }else{
            $data = Db::table("store_config")->where("type=9")->field("id,title,title_ru")->select();
        }
        $this->api_result(200, '请求成功', ['data' => $data]);
    }


    /**
     * @param Request $request
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 多语言工作台
     * @author: dongdong
     * @date: 2025/2/20 17:48
     */
    public function state_work(Request $request)
    {
        $param = $request->param();
        $user_id = $param['user_id'];
        $find = Db::connect("fast_mysql")->table("fa_user_staff")->where("user_id=$user_id")->field("id")->find();
        if (empty($find)) {
            $d['user_id'] = $user_id;
            Db::connect("fast_mysql")->table("fa_user_staff")->insert($d);
        }
        $data = Db::connect("fast_mysql")->table("fa_user_staff")->where("user_id=$user_id")->field("id,user_id,status,is_renzheng")->find();
        $data['member'] = Db::connect("fast_mysql")->table("fa_user")->where("id=$user_id")->field("id,username,username_ru,avatar,score,level")->find();
        $data['rating'] = Db::connect("fast_mysql")->table("fa_user_info")->where("user_id=$user_id")->value('rating');
        $this->api_result(200, '请求成功', ['data' => $data]);
    }


    /**
     * @param Request $request
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 身份认证回显
     * @author: dongdong
     * @date: 2025/2/20 18:00
     */
    public function state_find(Request $request)
    {
        $param = $request->param();
        $user_id = $param['user_id'];
        $data = Db::connect("fast_mysql")->table("fa_user_staff")->where("user_id=$user_id")->find();
        $data['city_arr'] = Db::connect("fast_mysql")->table("fa_area")->where(['id' => $data['city_id']])->find();
        $data['know_city_arr'] = Db::connect("fast_mysql")->table("fa_area")->where('id', "in", $data['know_city_id'])->select();
        $data['meeting'] = Db::connect("fast_mysql")->table("fa_code_table")->where("id", "in", $data['meeting_ids'])->field("name,name_ru")->select();
        $data['professional'] = Db::connect("fast_mysql")->table("fa_code_table")->where("id", "in", $data['professional_ids'])->field("name,name_ru")->select();
        $this->api_result(200, '请求成功', ['data' => $data]);
    }


    /**
     * @param Request $request
     * @throws DbException
     * @notes 身份认证保存
     * @author: dongdong
     * @date: 2025/2/20 20:06
     */
    public function state_save(Request $request)
    {
        $param = $request->param();

        $user_id = $param['user_id'];

        $find = Db::connect("fast_mysql")->table("fa_user_staff")->where("user_id=$user_id")->field("id")->find();
        if (empty($find)) {
            $d['user_id'] = $user_id;
            Db::connect("fast_mysql")->table("fa_user_staff")->insert($d);
        }


        $RemarkModel = new RemarkModel();
        $name_arr = $RemarkModel->translationAction($param['name'] ?? '');
        $d['name'] = $name_arr['zh'] ?? '';
        $d['name_ru'] = $name_arr['ru'] ?? '';

        $content_arr = $RemarkModel->translationAction($param['content'] ?? '');
        $d['content'] = $content_arr['zh'] ?? '';
        $d['content_ru'] = $content_arr['ru'] ?? '';

        $d['phone'] = $param['phone'] ?? '';
        $d['know_city_id'] = $param['know_city_id'] ?? '';

        $d['city_id'] = $param['city_id'] ?? '0';
        $d['avatar'] = $param['avatar'] ?? '';
        $fa_area = Db::connect("fast_mysql")->table("fa_area")->where(["id"=>$param['city_id']])->find();
        if($fa_area){
            $d['province_id'] = $fa_area['pid'];
            $d['country'] = $fa_area['country'];
        }

        $lang_arr = $RemarkModel->translationAction($param['lang'] ?? '');
        $d['request_lang'] = $lang_arr['zh'] ?? '';
        $d['request_lang_ru'] = $lang_arr['ru'] ?? '';

        $d['professional_ids'] = $param['professional_ids'] ?? '';

        $d['intention_score'] = $param['intention_score'] ?? 0;
        if ($d['intention_score']) {
            $d['min_score'] = 20;
            $d['max_score'] = $d['intention_score'];
        }
        $d['interval_score'] = $this->generateSequence($d['min_score'], $d['max_score']);
        $d['is_renzheng'] = 2; //'0未认证  1审核中 2已认证 '


        Db::connect("fast_mysql")->table("fa_user_staff")->where("user_id=$user_id")->update($d);

        Db::connect("fast_mysql")->table("fa_user")->where('id',$user_id)->update(['username'=>$d['name'],'username_ru'=>$d['name_ru'],'avatar'=>$param['avatar'] ?? '']);
        Db::connect("fast_mysql")->table("fa_user_info")->where('user_id',$user_id)->update(['area_id'=>$d['city_id']]);
        $this->api_result(200, '请求成功', ['data' => []]);
    }

    /**
     * @param $start
     * @param $end
     * @return string
     * @notes 检测积分区间
     * @author: dongdong
     * @date: 2025/2/20 20:07
     */
    public function generateSequence($start, $end)
    {
        // 确保输入是整数
        $start = (int)$start;
        $end = (int)$end;

        // 如果起始值大于结束值，交换它们
        if ($start > $end) {
            list($start, $end) = [$end, $start];
        }

        // 使用 range 函数生成步长为 20 的序列
        $sequence = range($start, $end, 20);

        // 将序列用逗号拼接成字符串
        return implode(',', $sequence);
    }


    /**
     * @param Request $request
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 关注翻译人员
     * @author: dongdong
     * @date: 2025/2/22 16:10
     */
    public function guanzhu(Request $request)
    {
        $param = $request->param();
        $user_id = $param['user_id'];
        $guanzhu_id = $param['guanzhu_user_id'];
        $user_guanzhu = Db::connect("fast_mysql")->table("fa_user_guanzhu")->where(['user_id' => $user_id, 'guanzhu_id' => $guanzhu_id])->find();

        $find = Db::connect("fast_mysql")->table("fa_user_guanzhu_group")->where("user_id=$user_id and is_no_group=1")->find();
        if (empty($find)) {
            $d['user_id'] = $user_id;
            $d['title'] = '未分组';
            $d['title_ru'] = 'Не сгруппировано';
            $d['create_at'] = date('Y-m-d H:i:s');
            $d['is_no_group'] = 1;
            Db::connect("fast_mysql")->table("fa_user_guanzhu_group")->insert($d);
        }

        $weifenzu = Db::connect("fast_mysql")->table("fa_user_guanzhu_group")->where("user_id=$user_id and is_no_group=1")->value('id');

        if (empty($user_guanzhu)) {
            $fa_user = Db::connect("fast_mysql")->table("fa_user")->where(['id' => $user_id])->find();
            if ($fa_user) {
                $dd['user_id'] = $user_id;
                $dd['guanzhu_id'] = $guanzhu_id;
                $dd['createtime'] = time();
                $dd['type'] = 1;
                $dd['release_type'] = 'user';
                $dd['version'] = $param['version'] ?? '';
                $dd['group_id'] = $weifenzu;
                $dd['keyword'] = $fa_user['username'] . ' ' . $fa_user['username_ru'];
                Db::connect("fast_mysql")->table("fa_user_guanzhu")->insert($dd);
            }
        } else {
            Db::connect("fast_mysql")->table("fa_user_guanzhu")->where(['user_id' => $user_id, 'guanzhu_id' => $guanzhu_id])->delete();
        }
        $this->api_result(200, '请求成功', ['data' => []]);

    }


    /**
     * @param Request $request
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 会议订单记录
     * @author: dongdong
     * @date: 2025/2/22 16:55
     */
    public function message_board_info(Request $request){
        $param = $request->param();
        $id = $param['id'];
        $find = Db::connect("fast_mysql")->table("fa_message_board")
            ->field("id,user_id,meeting_score_total,create_at,start_time,close_time,evaluate,evaluate_brand,content,content_ru")->where(["id"=>$id])->find();
        $find['title'] = $find['content'].'获得'.$find['meeting_score_total'].'积分';
        $find['title_ru'] = $find['content_ru'].'获得'.$find['meeting_score_total'].'积分';
        $find['comment_brand'] = explode(',',$find['evaluate_brand'])[0];

        $this->api_result(200, '请求成功', ['data' => $find]);
    }

    //会议订单记录
    public function message_board_list(Request $request){
        $param = $request->param();
        $user_id = $param['user_id'];
        $list = Db::connect("fast_mysql")->table("fa_message_board")
            ->field("id,user_id,meeting_score_total,create_at,start_time,close_time,evaluate,evaluate_brand,content,content_ru")->where(["user_id"=>$user_id])->select();
        $arr = [];
        foreach ($list as $k =>&$v){
            $v['title'] = $v['content'].'获得'.$v['meeting_score_total'].'积分';
            $v['title_ru'] = $v['content_ru'].'获得'.$v['meeting_score_total'].'积分';
            $v['comment_brand'] = explode(',',$v['evaluate_brand'])[0];
            array_push($arr,$v);
        }
        $total = Db::connect("fast_mysql")->table("fa_message_board")
            ->field("id,user_id,meeting_score_total,create_at,start_time,close_time,evaluate,evaluate_brand,content,content_ru")->where(["user_id"=>$user_id])->sum('meeting_score_total');

        $this->api_result(200, '请求成功', ['data' => $arr,'total'=>$total]);
    }



    /**
     * @param Request $request
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 员工列表
     * @author: dongdong
     * @date: 2025/2/24 10:54
     */
    public function staff(Request $request){
        $param = $request->param();
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;
        $page = ($page - 1) * $limit;

        $lang = $param['lang'] ?? '';
        $professional_ids = $param['professional_ids'] ?? '';
        $score = $param['score'] ?? '';

        $where_or = [];
        if($lang){
            $lang_arr = explode(',',$lang);
            foreach ($lang_arr as $k =>&$v){
                $where_or[] = ['request_lang', 'like', '%'.$v."%"];
            }
        }
        if($professional_ids){
            $professional_arr = explode(',',$professional_ids);
            foreach ($professional_arr as $k =>&$v){
                $where_or[] = ['professional_ids', 'like', '%'.$v."%"];
            }
        }
        if($score){
            $score_arr = explode(',',$score);
            foreach ($score_arr as $k =>&$v){
                $where_or[] = ['intention_score', 'like', '%'.$v."%"];
            }
        }


        $city_id = $param['city_id'] ?? '';
        $where = "user_id!=0 and is_renzheng=2";
        if($city_id){
            if(is_numeric($city_id)){
                $where .= " and city_id=$city_id";
            }else{
                $city_arr = explode(',',$city_id);
                if($city_arr){
                    $d_country = $city_arr[0];
                    $d_province = $city_arr[1];
                    $d_city = $city_arr[2];
                    if($d_city!='-1'){
                        $where .= " and city_id=$d_city";
                    }else{
                        if($d_province !='-1'){
                            $where .= " and province_id=$d_province";
                        }else{
                            $where .= " and country=$d_country";
                        }
                    }
                }
            }
        }
        $country = $param['country'] ?? '-1';
        if(isset($param['country'])&&($param['country']!='')){
            if($country!='-1'){
                $where .= " and country in ($country)";
            }
        }

        $list = Db::connect("fast_mysql")
            ->table("fa_user_staff")
            ->where($where_or)
            ->where($where)->order("rating desc")->limit($page,$limit)->select();

        $arr = [];
        foreach ($list as $k =>&$v){
            $v['avatar'] = Db::connect("fast_mysql")->table("fa_user")->where(['id' => $v['user_id']])->value('avatar');
            $v['city_arr'] = Db::connect("fast_mysql")->table("fa_area")->where(['id' => $v['city_id']])->find();
            $v['know_city_arr'] = Db::connect("fast_mysql")->table("fa_area")->where('id', "in", $v['know_city_id'])->select();
            $v['meeting'] = Db::connect("fast_mysql")->table("fa_code_table")->where("id", "in", $v['meeting_ids'])->field("name,name_ru")->select();
            $v['professional'] = Db::connect("fast_mysql")->table("fa_code_table")->where("id", "in", $v['professional_ids'])->field("name,name_ru")->select();
            array_push($arr,$v);
        }
        $this->api_result(200, '请求成功', ['data' => $arr]);
    }



}